import { useMemo, useState } from "react";
import { Form } from "antd";
import useMyContext from "./useContext";
import useGetState from "./useGetState";

const ACTIONS = {
  view: "查看",
  edit: "编辑",
  add: "新增",
};

const useCRUD = ({
  name,
  initForm = {},
  doCreate,
  doDelete,
  doUpdate,
  refresh,
}) => {
  const { messageApi } = useMyContext();
  const [modalVisible, setModalVisible] = useGetState(false); // 弹框显示
  /** 操作: add - 新增, edit - 删除, view - 查看 */
  const [modalAction, setModalAction] = useGetState("");
  const [modalLoading, setModalLoading] = useGetState(false);
  const modalTitle = useMemo(() => ACTIONS[modalAction] + name); // 弹窗标题
  const [tableSelections, setTableSelections] = useState([]); //表格第一项全选数组
  const [modalForm, setModalForm, getModalForm] = useGetState({ ...initForm });
  const [modalFormRef] = Form.useForm();

  //新增
  function handleAdd() {
    setModalAction("add");
    setModalVisible(true);
    setModalForm({ ...initForm });
  }

  //修改
  function handleEdit(row) {
    setModalAction("edit");
    setModalVisible(true);
    setModalForm({ ...row });
    modalFormRef.setFieldsValue({ ...row }); //设置表单的初始数据
  }

  //查看
  function handleView(row) {
    setModalAction("view");
    setModalVisible(true);
    setModalForm({ ...row });
    modalFormRef.setFieldsValue({ ...row }); //设置表单的初始数据
  }

  //保存
  async function handleSave() {
    if (!["edit", "add"].includes(modalAction)) {
      //错误的标识不进行任何处理
      setModalVisible(false);
      return;
    }
    try {
      await modalFormRef.validateFields();
      let params = modalFormRef.getFieldsValue();
      params = { ...params, ...modalForm }; //有的地方需要合并数据

      const actions = {
        add: {
          api: () => doCreate(params),
          cb: () => messageApi.success("新增成功"),
        },
        edit: {
          api: () => {
            params = { ...getModalForm(), ...params };
            return doUpdate(params);
          },
          cb: () => messageApi.success("编辑成功"),
        },
      };
      const action = actions[modalAction];
      setModalLoading(true);
      const { code, message } = await action.api();
      if (code === 0) {
        refresh();
      } else {
        throw message;
        return;
      }
      action.cb();
      setModalVisible(false);
      modalFormRef.resetFields(); //清空表单值
      setModalForm({}); //清空该表单值，防止每次提交携带之前的数据
    } catch (error) {
      messageApi.error(typeof error === "string" ? error : "更新或新建出错");
    } finally {
      setModalLoading(false);
    }
  }

  /**
   * 删除 (传入数组为批量删除, 传入单个 id 为普通删除)
   * @param {*} ids 主键数组 删除的数据id
   */
  function handleDelete(ids) {
    if (!ids || (Array.isArray(ids) && !ids.length)) {
      messageApi.info("请选择要删除的数据");
      return;
    }
    const callDeleteApi = async () => {
      try {
        setModalLoading(true);
        const data = await doDelete(ids);
        if (data?.code === 0) {
          messageApi.open({
            type: "success",
            content: "删除成功",
          });
        } else {
          messageApi.open({
            type: "error",
            content: `${data?.message}`,
          });
        }
        //重新刷新获取表单数据
        await refresh();
      } catch (error) {
        console.log(error);
        messageApi.open({
          type: "error",
          content: "删除失败",
        });
      } finally {
        setModalLoading(false);
      }
    };
    callDeleteApi();
  }
  return {
    modalVisible,
    setModalVisible,
    modalAction,
    setModalAction,
    modalLoading,
    setModalLoading,
    modalTitle,
    modalForm,
    setModalForm,
    modalFormRef,
    tableSelections,
    setTableSelections,
    handleDelete,
    handleAdd,
    handleEdit,
    handleView,
    handleSave,
    clearFormFields: () => modalFormRef.resetFields(),
    getModalForm,
  };
};

export default useCRUD;
